﻿using CYZH.CommandAssembly.JsonObject;
using CYZH.Common;
using CYZH.Service.Drought;
using SuperWebSocket;
using SuperWebSocket.SubProtocol;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CYZH.CommandAssembly.Command
{
    public class CVI : JsonSubCommand<MODISParam>
    {
        protected override void ExecuteJsonCommand(WebSocketSession session, MODISParam commandInfo)
        {
            double[] ext = { 0, 0, 0, 0 };
            OutRasterConfigElement rce = Common.ConfigHelper.GetConfigParamByXzqhCode(commandInfo.XzqhCode);

            string strminx = rce.Extents;
            string[] strext = strminx.Split(',');

            double MinX = Convert.ToDouble(strext[0]);
            double MinY = Convert.ToDouble(strext[1]);
            double MaxX = Convert.ToDouble(strext[2]);
            double MaxY = Convert.ToDouble(strext[3]);
            ext[0] = MinX;// { MinX, MinY, MaxX, MaxY };
            ext[1] = MinY;
            ext[2] = MaxX;
            ext[3] = MaxY;

            string aoifile = rce.ShpFile;
            string cldaoiFile = rce.ChildShpFile;
            string layername = commandInfo.XzqhCode + "_" + commandInfo.FileTime + "_cvi";
            string strextents = ext[0] + ", " + ext[1] + ", " + ext[2] + ", " + ext[3];

            //string smouth = "", sdays = "", sxun = "", stype = "";
            //if (commandInfo.FileTime.Length == 4)//2013
            //{
            //    stype = "year";
            //}
            //if (commandInfo.FileTime.Length == 6)//201304
            //{
            //    smouth = commandInfo.FileTime.Substring(4);
            //    stype = "mouth";
            //}
            //if (commandInfo.FileTime.Length == 8)//20130401
            //{
            //    smouth = commandInfo.FileTime.Substring(4, 2);
            //    sxun = commandInfo.FileTime.Substring(6);
            //    stype = "xun";
            //}

            //查询数据是否已经做过
            List<ModisResultBean> res = CommonService.queryRasterResult(commandInfo.XzqhCode, commandInfo.FileTime, "CVI", "days",null);
            if (res.Count != 0)
            {
                //string filename = res[0].FileName;
                //string filepath = FileOper.GetExitsModisFilePath("MOD09Q1", filename, "CVI", "map");
                //string unixfile1 = filepath.Replace('\\', '/');
                MapFileResult resultstate1 = new MapFileResult();
                resultstate1.process = "100";
                resultstate1.state = "0";
                resultstate1.value = "success";
                resultstate1.LayerName = res[0].LayerName;
                resultstate1.Extents = strextents;
                //resultstate1.MapFile = unixfile1;
                SendJsonMessage(session, resultstate1);
                Logger.Singleton.Debug(String.Format("CVI结果已经存在."));
                return;
            }

            //string ndvifile = "", avgfile = "";
            //foreach (string f in commandInfo.MODISFileList)
            //{
            //    if (f.Contains("NDVI"))
            //    {
            //        ndvifile = FileOper.GenSHINDVI(f);
            //    }
               
            //}
            //avgfile = FileOper.GenSHINDVI(commandInfo.AvgFile);
            //if (!File.Exists(ndvifile) || !File.Exists(avgfile))
            //{
            //    Logger.Singleton.Debug("文件不存在...");
            //    ResultState errstate = new ResultState();
            //    errstate.process = "100";
            //    errstate.state = "-1";
            //    errstate.value = ndvifile+"或"+ avgfile +"文件不存在...";
            //    SendJsonMessage(session, errstate);
            //    return;
            //}
            List<string> files = new List<string>();
            foreach (string filename in commandInfo.MODISFileList)
            {

                string filepath = FileOper.GetExitsModisFilePath(filename, "NDVI");
                if (!File.Exists(filepath))
                {
                    continue;
                }
                files.Add(filepath);
            }
            if (files.Count == 0)
            {
                Logger.Singleton.Debug("输入文件不存在...");
                ResultState errstate = new ResultState();
                errstate.process = "100";
                errstate.state = "-1";
                errstate.value = "输入文件不存在...";
                SendJsonMessage(session, errstate);
                return;
            }
            string avgfile = FileOper.GenPreNDVI(commandInfo.XzqhCode,commandInfo.AvgFile);
            if (!File.Exists(avgfile))
            {
                Logger.Singleton.Debug("文件不存在...");
                ResultState errstate = new ResultState();
                errstate.process = "100";
                errstate.state = "-1";
                errstate.value =  avgfile + "文件不存在...";
                SendJsonMessage(session, errstate);
                return;
            }
            string aoiShpFile = FileOper.GenAOIFilePath(aoifile);
            string cldaoiShpFile = FileOper.GenAOIFilePath(cldaoiFile);
            string sfilename = FileOper.GenModisFilePath(layername, "CVI");
            CVIService cvi = new CVIService();
            int rst = cvi.CalculateCVI(files[0], avgfile, aoiShpFile, sfilename);
            if (rst != 0)
            {
                ResultState errstate = new ResultState();
                errstate.process = "100";
                errstate.state = "-1";
                errstate.value = "计算CVI出错!";
                SendJsonMessage(session, errstate);
                return;
            }
            
            //生成map文件
            string mapfile = MapFileUtils.GenMapFile( "CVI", strextents.Replace(',', ' '), layername);
            //生成统计信息，按当前行政区划的下一级统计
            string str_static = CommonService.RegionaStatistics(sfilename, cldaoiShpFile);
            //保存到数据库
            CommonService.saveRasterResult(mapfile, commandInfo.FileTime, commandInfo.XzqhCode, layername, "CVI", "", commandInfo.FileTime.Substring(4), "", "days", str_static,null);
            
            //string unixfile = mapfile.Replace('\\', '/');
            MapFileResult resultstate2 = new MapFileResult();
            resultstate2.process = "100";
            resultstate2.state = "0";
            resultstate2.value = "success";
            resultstate2.LayerName = layername;
            resultstate2.Extents = strextents;
            //resultstate2.MapFile = unixfile;
            SendJsonMessage(session, resultstate2);
            Logger.Singleton.Debug(String.Format("数据合并结束，生成MAP文件路径：{0}.", mapfile));

        }
    }
}
